package com.cosma.xiaohashu.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.cosma.framework.common.exception.BizException;
import com.cosma.framework.common.response.Response;
import com.cosma.xiaohashu.auth.constant.RedisKeyConstants;
import com.cosma.xiaohashu.auth.enums.ResponseCodeEnum;
import com.cosma.xiaohashu.auth.model.vo.veriticationcode.SendVerificationCodeReqVO;
import com.cosma.xiaohashu.auth.service.VerificationCodeService;
import com.cosma.xiaohashu.auth.sms.AlinyunSmsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


/**
 * @author yusu_
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private AlinyunSmsHelper alinyunSmsHelper;


    /**
     * 发送短信验证码
     * @param sendVerificationCodeReqVO
     * @return
     */
    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        //获取手机号
        String phone = sendVerificationCodeReqVO.getPhone();
        //构建验证码 redis key
        String key = RedisKeyConstants.buildVerificationCodeKey(phone);
        //判断是否已发送验证码
        boolean isSent = redisTemplate.hasKey(key);
        if(isSent){
            //若之前的验证码未过期，则提示发送频繁
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }
        //生成6位随机数字验证码
        String verificationCode = RandomUtil.randomNumbers(6);
        //调用第三方发送短信服务
        threadPoolTaskExecutor.submit(()->{
            String signName = "阿里云短信测试";
            String templateCode = "SMS_154950909";
            String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
            alinyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
        });
        //存储验证码到redis,并设置过期时间3分钟
        redisTemplate.opsForValue().set(key,verificationCode,3*60, TimeUnit.SECONDS);

        return Response.success();
    }
}
